import React, { Component } from 'react';
import { Table, Pagination, Balloon, Icon, Field, Dialog, Form, Input, Select, Feedback} from '@icedesign/base';
import Api from '../../../../Api/Api';
import Ajax from '../../../../Ajax';
import PropTypes from 'prop-types';

const FormItem = Form.Item;
const getData = () => {
  return Array.from({ length: 10 }).map((item, index) => {
    return {
      id: index + 1,
      // orderID: `12022123${index}`,
      name: `用户${index + 1}`,
      title: '普通用户',
      date: `2018-06-${index + 1}`,
      // endDate: `2018-06-${index + 1}`,
      // validData: `2018-06-${index + 1}`,
      // category: '皮肤科',
      state: '已审核',
      approver: 'admin',
      approvalData: `2018-06-${index + 1}`,
    };
  });
};

export default class Home extends Component {
  static displayName = 'Home';

  static propTypes = {
    dataSource: PropTypes.array,
    total: PropTypes.number,
    changeDataSource: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      visible: false,
    };
    this.field = new Field(this);
  }

  handlePagination = (current) => {
    this.setState({
      current,
    });
  };

  handleSort = (dataIndex, order) => {
    const dataSource = this.props.dataSource.sort((a, b) => {
      const result = a[dataIndex] - b[dataIndex];
      if (order === 'asc') {
        return result > 0 ? 1 : -1;
      }
      return result > 0 ? -1 : 1;
    });
    this.props.changeDataSource(dataSource, this.props.total)
  };

  handleEditClick = (value) => {
    var valueObject = {};
    this.props.dataSource.forEach(val => {
      if (val['id']===value) {
        Object.assign(valueObject, val)
      }
    });
    console.log(valueObject);
    this.field.setValues(valueObject);
    this.setState({
      visible: true
    });
  }

  handleSubmit = () => {
    this.field.validate((errors, values) => {
      var url = Api.changeUser(values);
      console.log(url);
      Feedback.toast.show({
        type: 'loading',
        content: '正在修改'
      });
      Ajax.get(url)
        .then((res) => {
          Feedback.toast.hide();
          if (res.data.code) {
            var oldDataSource = this.props.dataSource;
            var newDataSource = [];
            oldDataSource.forEach((val, index) => {
              if (val.id === values.id) {
                newDataSource.push(values);
              } else {
                newDataSource.push(val);
              }
            });
            Feedback.toast.show({
              content: res.data.message,
              afterClose: () => {
                this.props.changeDataSource(newDataSource, this.props.total);
                this.onClose();
              }
            })
            
            // console.log(res.data)
          }
        })
    })
  }

  renderOper = (value) => {
    // console.log(value)
    return (
      <div style={styles.oper}>
        <Icon type="edit" size="small" style={styles.editIcon} onClick={this.handleEditClick.bind(this, value)}/>
      </div>
    );
  };
  // 编辑商品dialog框关闭事件
  onClose = () => {
    this.setState({
      visible: false
    });
  };

  renderDialog = () => {
    const init = this.field.init;
    const formItemLayout = {
      labelCol: {
        fixedSpan: 6,
      },
      wrapperCol: {
        span: 14,
      },
    };
    return(
      <Dialog
        style={{ width: 640 }}
        visible={this.state.visible}
        onOk={this.handleSubmit}
        onCancel={this.onClose}
        onClose={this.onClose}
        title="编辑用户"
        closable="esc,mask,close"
      >
         <Form direction="ver">
            <FormItem label="用户名称：" {...formItemLayout}>
              <Input
              {...init('username', {
                rules: [{ required: true, message: '必填选项' }],
              })}
              readOnly={true}
              />
            </FormItem>

            <FormItem label="用户注册时间：" {...formItemLayout}>
              <Input
               
              {...init('registerdate', {
                rules: [{ required: true, message: '必填选项' }],
              })}
              />
            </FormItem>

            <FormItem label="会员开始时间：" {...formItemLayout}>
              <Input
               
              {...init('vipstartdate', {
                rules: [{ required: true, message: '必填选项' }],
              })}
              />
            </FormItem>

            <FormItem label="会员结束时间：" {...formItemLayout}>
              <Input
               
              {...init('vipenddate', {
                rules: [{ required: true, message: '必填选项' }],
              })}
              />
            </FormItem>

            <FormItem label="用户类型：" {...formItemLayout}>
              <Select
                {...init('usertype', {
                  rules: [{ required: true, message: '必填选项' }],
                })}
              >
                <div value="普通用户">普通用户</div>
                <div value="会员用户">会员用户</div>
              </Select>
            </FormItem>
          </Form>
      </Dialog>
    )
  }

  handerSelectOnChange = (values) => {
    var newStateValue = this.state.value;
    Object.assign(newStateValue, {"usertype": values})
    this.setState({
      value: newStateValue
    })
  }

  render() {
    const { dataSource, total } = this.props;
    const DialogEdit = this.renderDialog();
    // console.log(this)
    return (
      <div style={styles.tableContainer}>
        <Table
          dataSource={dataSource}
          onSort={this.handleSort}
          hasBorder={false}
          className="custom-table"
        >
          <Table.Column
            width={100}
            lock="left"
            title="序列号"
            dataIndex="id"
            sortable
            align="center"
          />
          <Table.Column width={100} title="用户名称" dataIndex="username" />
          <Table.Column width={100} title="用户类型" dataIndex="usertype" />
          <Table.Column width={200} title="用户注册时间" dataIndex="registerdate" />
          <Table.Column width={200} title="会员开始日期" dataIndex="vipstartdate" />
          <Table.Column width={200} title="会员结束日期" dataIndex="vipenddate" />
          <Table.Column
            width={100}
            title="操作"
            cell={this.renderOper}
            lock="right"
            align="center"
            dataIndex="id"
          />
        </Table>
        {DialogEdit}
        <Pagination
          style={styles.pagination}
          current={this.state.current}
          onChange={this.handlePagination}
          total={total}
        />
      </div>
    );
  }
}

const styles = {
  tableContainer: {
    background: '#fff',
    paddingBottom: '10px',
  },
  pagination: {
    margin: '20px 0',
    textAlign: 'center',
  },
  editIcon: {
    color: '#999',
    cursor: 'pointer',
  },
  circle: {
    display: 'inline-block',
    background: '#28a745',
    width: '8px',
    height: '8px',
    borderRadius: '50px',
    marginRight: '4px',
  },
  stateText: {
    color: '#28a745',
  },
};
